/*
 * File Name:               CachePool.cs
 *
 * Description:             高可用性类缓存池
 * 							有效减少内存碎片的产生
 * * 						// todo GC 和 自动GC(例如久了没使用就删掉)
 * Author:                  lisiyu
 * Create Date:             2016/11/18
 */

using System;
using System.Collections.Generic;

public class XCachePool : SingletonTemplate<XCachePool>
{
    private Dictionary<Type, Stack<ICache>> mPool = new Dictionary<Type, Stack<ICache>>();

    public T pop<T>(object args = null) where T : class, ICache, new()
    {
        T ret = null;
        Type type = typeof(T);
        if (mPool.ContainsKey(type))
        {
            if (mPool[type].Count > 0)
            {
                ret = mPool[type].Pop() as T;
                ret.onSpawn(args);
                return ret;
            }
        }

        ret = new T();
        ret.onSpawn(args);
        return ret;
    }

    public void push(ICache obj)
    {
        Type type = obj.GetType();
        if (!mPool.ContainsKey(type))
        {
            mPool.Add(type, new Stack<ICache>());
        }

        obj.onRecycle();
        mPool[type].Push(obj);
    }
}